package com.whpost.api.filter;

import com.whpost.service.tools.ToolBean;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;

import java.util.HashSet;
import java.util.Set;

/**
 * @author 张瑶
 * @Description: xss非法标签过滤
 * @date 2018/5/16 20:03
 */
public class XssFilterUtil {

    /**
     * 使用自带的basicWithImages 白名单
     * 允许的便签有a,b,blockquote,br,cite,code,dd,dl,dt,em,i,li,ol,p,pre,q,small,span,
     * strike,strong,sub,sup,u,ul,img
     * 以及a标签的href,img标签的src,align,alt,height,width,title属性
     */
    private static final Whitelist whitelist = Whitelist.basicWithImages();

    private static String key  = "'|and|exec|execute|insert|select|delete|update|count|drop|*|%|chr|mid|master|truncate|" +
            "char|declare|sitename|net user|xp_cmdshell|;|or|-|+|,|like'|and|exec|execute|insert|create|drop|" +
            "table|from|grant|use|group_concat|column_name|" +
            "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|" +
            "chr|mid|master|truncate|char|declare|or|;|-|--|+|,|like|//|/|%|#|script|iframe|alert|<|>|on|location|document";//过滤掉的sql关键字，可以手动添加
    private static Set<String> notAllowedKeyWords = new HashSet<String>(0);
    private static String replacedString="INVALID";
    static {
        String keyStr[] = key.split("\\|");
        for (String str : keyStr) {
            notAllowedKeyWords.add(str);
        }
    }

    /** 配置过滤化参数,不对代码进行格式化 */
    private static final Document.OutputSettings outputSettings = new Document.OutputSettings().prettyPrint(false);
    static {
        // 富文本编辑时一些样式是使用style来进行实现的
        // 比如红色字体 style="color:red;"
        // 所以需要给所有标签添加style属性
        whitelist.addAttributes(":all", "style");
    }

    public static String clean(String content,String url) {
        ToolBean.info("开始对地址【"+url+"】的内容【"+content+"】进行clean>>>");
        String rtn = "";

        content = Jsoup.clean(content, "", whitelist, outputSettings);

        rtn = cleanSqlKeyWords(content,url);

        ToolBean.info("开始对地址【"+url+"】的内容【"+content+"】进行clean>>>结束，返回【"+rtn+"】");
        return rtn;
    }

    private static String cleanSqlKeyWords(String value,String url) {
        ToolBean.info("开始对地址【"+url+"】的内容【"+value+"】cleanSqlKeyWords>>>");
        String paramValue = value;
        for (String keyword : notAllowedKeyWords) {
            if (paramValue.length() > 0
                    && (paramValue.contains(" "+keyword)||paramValue.contains(keyword+" ")||paramValue.contains(" "+keyword+" "))) {
                paramValue = StringUtils.replace(paramValue, keyword, replacedString);
               /* ToolBean.info(url + "已被过滤，因为参数中包含不允许sql的关键词(" + keyword
                        + ")"+";参数："+value+";过滤后的参数："+paramValue);*/
            }
        }
        //ToolBean.info("开始对地址【"+url+"】的内容【"+value+"】cleanSqlKeyWords>>>结束，返回【"+paramValue+"】");
        return paramValue;
    }

}
